const { myCourse } = require('../../api/course')
const { API_OK } = require('../../utils/setting')
const app = getApp()

Page({
  data: {
    loading: false,
    courseList: []
  },
  pageData: {
    page: 1,
    canLoadMore: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    this.setData({ loading: true })
    if (wx.getStorageSync('token')) {
      this.getCourseList()
    } else {
      app.tokenReadyCallback = this.getCourseList
      app.getTokenFailedCallback = () => {
        this.setData({ loading: false })
      }
    }
  },
  onReachBottom() {
    if (!this.pageData.canLoadMore) return
    this.pageData.page += 1
    this.setData({ loading: true })
    this.getCourseList()
  },
  async getCourseList() {
    try {
      const res = await myCourse()
      console.log(res)
      if (res.code === API_OK) {
        const list = res.data.data.filter(item => item.courses)
        this.setData({
          loading: false,
          courseList: list.map(item => {
            return {
              id: item.courses_id,
              image: (item.courses.image && item.courses.image.length) && item.courses.image[0].file_path,
              courseName: item.courses.course_name,
              hideBottom: true
            }
          })
        })
      }
    } catch(err) {
      console.warn(err)
      this.setData({ loading: false })
    }
  }
})
